# -*- coding: utf-8 -*-

from odoo import models, fields, api
import akshare as ak


class CovHistory(models.Model):
    _name = "cov.history"
    _description = "中国历史时点数据"

    cov_date = fields.Date(string='日期')
    cov_confirm = fields.Integer(string='新增确诊人数')
    cov_suspect = fields.Integer(string='新增疑似人数')
    cov_heal = fields.Integer(string='新增治愈人数')
    cov_dead = fields.Integer(string='新增死亡人数')
    cov_severe = fields.Integer(string='新增重症人数')
    cov_abroad = fields.Integer(string='境外输入')

    def get_cov_history_data(self):
        """
        自动任务获取中国历史时点数据
        :return:
        """
        covid_19_163_df = ak.covid_19_163(indicator="中国历史时点数据")
        cov_data = {}
        for inx in covid_19_163_df.index:
            col = covid_19_163_df.loc[inx]
            vals = {
                'cov_date': inx,
                'cov_confirm': col[0],
                'cov_suspect': col[1],
                'cov_heal': col[2],
                'cov_dead': col[3],
                'cov_severe': col[4],
                'cov_abroad': col[6],

            }
            cov_data[inx] = vals
            # self.create(vals)
        self_record = self.search([('cov_date', 'in', list(set(cov_data.keys())))])
        self_record_dict = dict(list(map(lambda r: (r.cov_date.strftime("%Y-%m-%d"), r.id), self_record)))
        create_list = []
        for r_date, r_val in cov_data.items():
            self_r_id = self_record_dict.get(r_date, False)
            if not self_r_id:
                create_list.append(r_val)
            else:
                current = self.browse(self_r_id)
                current.write(r_val)
        if create_list:
            self_record.create(create_list)
        print(covid_19_163_df.columns)
        # print(inxs)
